<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @package  	PyroCMS
 * @subpackage  Categories
 * @category  	Module
 * @author  	PyroCMS Dev Team
 */
class Admin_Message extends Admin_Controller {

	/**
	 * The current active section
	 * @access protected
	 * @var int
	 */
	protected $section = 'message-detail';
	protected $_ci;
	protected $_currentUserGroup;
	protected $_currentUserName = '';
	protected $_curentUserZones;
	protected $_escortIdList;
	/**
	 * Array that contains the validation rules
	 * @access protected
	 * @var array
	 */
	protected $validation_rules = array(
		array(
			'field' => 'message',
			'label' => 'lang:escort_thread_message_label',
			'rules' => 'trim|required'
		),
	);
	
	/**
	 * The constructor
	 * @access public
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
		
		$this->load->library('form_validation');
		$this->_ci = &get_instance();
		$this->load->model('escort_message_threads_m');
		$this->load->model('escort_messages_m');
		$this->load->model('groups_m');
		
		$this->_currentUserGroup = $this->_ci->ion_auth->get_user()->group;
		$this->_currentUserName = $this->_ci->ion_auth->get_user()->username;
		$this->_curentUserZones = $this->_ci->escort_user_roles_n_zones_entity->getUserRolesNZones($this->_currentUserName);
		$this->_escortIdList = $this->_ci->user_entity->getEscortIdListByAdmin($this->_currentUserName, $this->_currentUserGroup, $this->_curentUserZones);
		
		$this->lang->load('message');
		$this->lang->load('message_thread');
		// Load the validation library along with the rules
		$this->load->library('form_validation');
		$this->form_validation->set_rules($this->validation_rules);
		$this->template->set_partial('shortcuts', 'admin/partials/shortcuts')
		->append_metadata(js('escort.message.js', 'message'))
		->append_metadata(css('escort.message.css', 'message'));
	}
	
	/**
	 * Index method, lists all categories
	 * @access public
	 * @return void
	 */
	public function index($thread_id)
	{
		$ci = &get_instance();
		// Validate the data
		if ($this->form_validation->run())
		{
			$this->escort_messages_m->insert(array(
				'sender'	=>$ci->ion_auth->get_user()->username, 
				'sent_time'	=> time(),
				'message'	=> $this->input->post('message'),
				'read'		=> 0,
				'thread_id'	=> $thread_id
			))
			? $this->session->set_flashdata('success', sprintf( lang('escort_message_add_success'), $this->input->post('message')) )
			: $this->session->set_flashdata('error', lang('escort_news_cat_add_error'));
			$ci = &get_instance();
			do_log(LOG_ACTION_BACKEND, 0, $ci->ion_auth->get_user()->username, 'escort_log_reply_message_action', array($thread_id));
			redirect('admin/message/message/index/'.$thread_id);
		}
		
		// Loop through each validation rule
		foreach ($this->validation_rules as $rule)
		{
			$post->{$rule['field']} = set_value($rule['field']);
		}
		
		$this->pyrocache->delete_all('modules_m');
		
		//$thread = $this->escort_message_threads_m->get_thread($thread_id, $ci->ion_auth->get_user()->group);
		
		if($this->_currentUserGroup != USER_ADMIN && $this->_currentUserGroup != USER_COUNTRY_MANAGER){
			$thread = $this->escort_message_threads_m->get_thread($thread_id,$ci->ion_auth->get_user()->group);
		}else{
			$thread = $this->escort_message_threads_m->get($thread_id);
		}
		$thread or die();
		if(!in_array($thread->escort_id, $this->_escortIdList)){
			die();
		}
		
		// Create pagination links
		$total_rows = $this->escort_messages_m->count_by('thread_id', $thread_id);
		$pagination = create_pagination('admin/message/message/index/'.$thread_id, $total_rows, NULL, 6);
			
		// Using this data, get the relevant results
		$messages = $this->escort_messages_m->where('thread_id', $thread_id)->order_by('sent_time', 'desc')->limit($pagination['limit'])->get_all();

		$this->template
			->title($this->module_details['name'], lang('escort_message_list_title'))
			->set('messages', $messages)
			->set('thread', $thread)
			->set('post', $post)
			->set('pagination', $pagination)
			->build('admin/message/index', $this->data);
	}
	
	/**
	 * Delete method, deletes an existing category (obvious isn't it?)
	 * @access public
	 * @param int id The ID of the category to edit
	 * @return void
	 */
	public function delete($thread_id = 0,$message_id = 0)
	{	
		$id_array = (!empty($message_id)) ? array($message_id) : $this->input->post('action_to');
		
		if($this->_currentUserGroup != USER_ADMIN && $this->_currentUserGroup != USER_COUNTRY_MANAGER){
			$thread = $this->escort_message_threads_m->get_thread($thread_id,$ci->ion_auth->get_user()->group);
		}else{
			$thread = $this->escort_message_threads_m->get($thread_id);
		}
		$thread or die();
		if(!in_array($thread->escort_id, $this->_escortIdList)){
			die();
		}
		
		// Delete multiple
		if (!empty($id_array))
		{
			$deleted = 0;
			$to_delete = 0;
			foreach ($id_array as $message_id)
			{
				if ($this->escort_messages_m->delete($message_id))
				{
					$deleted++;
					$ci = &get_instance();
					do_log(LOG_ACTION_BACKEND, 0, $ci->ion_auth->get_user()->username, 'escort_log_delete_sub_message_action', array($message_id));
				}
				else
				{
					$this->session->set_flashdata('error', sprintf(lang('escort_message_mass_delete_error'), $message_id));
				}
				$to_delete++;
			}
			
			if ( $deleted > 0 )
			{
				$this->session->set_flashdata('success', sprintf(lang('escort_message_mass_delete_success'), $deleted, $to_delete));
			}
		}		
		else
		{
			$this->session->set_flashdata('error', lang('escort_message_no_select_error'));
		}
		
		redirect('admin/message/message/index/'.$thread_id);
	}
		
	/**
	 * Callback method that checks the title of the category
	 * @access public
	 * @param string title The title to check
	 * @return bool
	 */
	public function _check_title($title = '')
	{
		if ($this->escort_news_categories_m->check_title($title))
		{
			$this->form_validation->set_message('_check_title', sprintf(lang('escort_news_cat_already_exist_error'), $title));
			return FALSE;
		}

		return TRUE;
	}
	
	/**
	 * Create method, creates a new category via ajax
	 * @access public
	 * @return void
	 */
	public function create_ajax()
	{
		// Loop through each validation rule
		foreach ($this->validation_rules as $rule)
		{
			$category->{$rule['field']} = set_value($rule['field']);
		}
		
		$this->data->method = 'create';
		$this->data->category =& $category;
		
		if ($this->form_validation->run())
		{
			$id = $this->escort_news_categories_m->insert_ajax($_POST);
			
			if ($id > 0)
			{
				$message = sprintf( lang('escort_news_cat_add_success'), $this->input->post('category'));
			}
			else
			{
				$message = lang('escort_news_cat_add_error');
			}

			return $this->template->build_json(array(
				'message'		=> $message,
				'category'			=> $this->input->post('category'),
				'category_id'	=> $id,
				'status'		=> 'ok'
			));
		}	
		else
		{
			// Render the view
			$form = $this->load->view('admin/categories/form', $this->data, TRUE);

			if ($errors = validation_errors())
			{
				return $this->template->build_json(array(
					'message'	=> $errors,
					'status'	=> 'error',
					'form'		=> $form
				));
			}

			echo $form;
		}
	}
	function mark_message(){
		$message_id = $this->input->post("message_id");
		$ci = &get_instance();
		if($this->_currentUserGroup != USER_ADMIN && $this->_currentUserGroup != USER_COUNTRY_MANAGER){
			$message = $this->escort_messages_m->get_message($message_id,$ci->ion_auth->get_user()->group);
		}else{
			$message = $this->escort_messages_m->get($message_id);
		}
		$message or die();
		$result = array();
		if($message->read){
			$message->read = 0;
			$result['text'] = lang('escort_thread_mark_as_read_label');
			$result['message'] = lang('escort_message_mark_as_unread_success');
		}else{
			$message->read = 1;
			$result['text'] = lang('escort_thread_mark_as_unread_label');
			$result['message'] = lang('escort_message_mark_as_read_success');
		}
		if($this->escort_messages_m->update($message->id, array(
						'sender'	=>$message->sender,
						'sent_time'	=> $message->sent_time,
						'message'	=> $message->message,
						'read'		=> $message->read,
						'thread_id'	=> $message->thread_id
		))){
			$ci = &get_instance();
			if($message->read){
				do_log(LOG_ACTION_BACKEND, 0, $ci->ion_auth->get_user()->username, 'escort_log_mark_as_read_sub_message_action', array($message->id));
			}else{
				do_log(LOG_ACTION_BACKEND, 0, $ci->ion_auth->get_user()->username, 'escort_log_mark_as_unread_sub_message_action', array($message->id));
			}
			$count = $this->escort_messages_m->check_read(0, $message->thread_id);
		
			if(!$count){
				$this->escort_message_threads_m->update($message->thread_id, array('status' => 1));
				do_log(LOG_ACTION_BACKEND, 0, $ci->ion_auth->get_user()->username, 'escort_log_mark_as_read_message_action', array($message->thread_id));
			}else{
				$this->escort_message_threads_m->update($message->thread_id, array('status' => 0));
				do_log(LOG_ACTION_BACKEND, 0, $ci->ion_auth->get_user()->username, 'escort_log_mark_as_unread_message_action', array($message->thread_id));
			}
			$result['result'] = true;
		}else{
			$result['result'] = false;
			$result['message'] = lang('escort_message_mark_error');
		}
		echo json_encode($result);
	}
}